package com.mx.tool.form.window;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mx.tool.util.NotifyUtil;
import com.mx.tool.util.PropertiesUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class FanyiWindow {

    private JPanel jPanel;
    private JTextArea zhTextArea;
    private JTextArea enTextArea;
    private JComboBox<String> comboBox;
    private JButton button;
    private JTextField securityKeyField;
    private JButton saveButton;
    private JTextField appIdField;
    private final static String APP_ID_KEY = "mx.translate.appId";
    private final static String SECURITY_KEY_KEY = "mx.translate.securityKey";

    private static final Map<String, String> MAP = new HashMap<>();

    static {
        MAP.put("英文", "en");
        MAP.put("中文", "zh");
        MAP.put("西班牙文", "spa");
        MAP.put("法文", "fr");
        MAP.put("德文", "de");
        MAP.put("俄文", "ru");
        MAP.put("日文", "jp");
        MAP.put(" 韩文", "kor");
    }

    public JPanel getContent() {
        return jPanel;
    }


    public FanyiWindow() {
        appIdField.setText(PropertiesUtil.get(APP_ID_KEY));
        securityKeyField.setText(PropertiesUtil.get(SECURITY_KEY_KEY));

        saveButton.addActionListener(e -> {
            String appId = appIdField.getText();
            String securityKey = securityKeyField.getText();
            if (StringUtils.isBlank(appId) || StringUtils.isBlank(securityKey)) {
                NotifyUtil.warning("请先设置appId和securityKey");
                return;
            }
            PropertiesUtil.put(APP_ID_KEY, appId);
            PropertiesUtil.put(SECURITY_KEY_KEY, securityKey);
            NotifyUtil.info("保存成功");
        });

        button.addActionListener(e -> {
            String text = zhTextArea.getText();
            if (StringUtils.isBlank(text)) {
                NotifyUtil.warning("请输入要翻译的内容");
                return;
            }
            String appId = appIdField.getText();
            String securityKey = securityKeyField.getText();
            if (StringUtils.isBlank(appId) || StringUtils.isBlank(securityKey)) {
                NotifyUtil.warning("请先设置appId和securityKey");
                return;
            }
            String to = MAP.get(Convert.toStr(comboBox.getSelectedItem()));
            //翻译
            String result = translate(appId, securityKey, to, text);
            if(StringUtils.isBlank(result)){
                NotifyUtil.error("翻译出错，请稍候重试");
                return;
            }
            JSONObject resultObject = JSONObject.parseObject(result);
            if(StringUtils.isNotBlank(resultObject.getString("error_code"))){
                NotifyUtil.error("翻译出错，请稍候重试");
                return;
            }
            JSONArray jsonArray = resultObject.getJSONArray("trans_result");
            if(jsonArray == null){
                NotifyUtil.error("翻译出错，请稍候重试");
                return;
            }
            StringBuilder sb = new StringBuilder();
            for(Object o : jsonArray){
                JSONObject tranObj = (JSONObject) o;
                sb.append(tranObj.getString("dst")).append("\n");
            }
            enTextArea.setText(StringEscapeUtils.unescapeJava(sb.toString()));
        });
    }


    private String translate(String appId, String securityKey, String to, String text) {
        try {
            String query = URLEncoder.encode(text, "UTF-8");
            String salt = RandomUtil.randomString(10);
            String sign = SecureUtil.md5(appId + text + salt + securityKey);
            String urlStr = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + query + "&from=auto&to=" + to + "&appid=" + appId + "&salt=" + salt + "&sign=" + sign;
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000); // 设置连接超时时间为5秒
            conn.setReadTimeout(5000); // 设置读取超时时间为5秒
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            } finally {
                conn.disconnect(); // 在finally块中确保连接被关闭
            }
        } catch (Exception e) {
            NotifyUtil.error("翻译出错，请稍候重试");
            return null;
        }
    }


}
